package com.leo.erp.web.user;

import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.leo.erp.dto.TenantExecution;
import com.leo.erp.dto.UserExecution;
import com.leo.erp.entity.User;
import com.leo.erp.enums.UserStateEnum;
import com.leo.erp.service.LogService;
import com.leo.erp.service.TenantService;
import com.leo.erp.service.UserService;
import com.leo.erp.util.GlobalRuntimeException;
import com.leo.erp.util.HttpServletRequestUtil;
import com.leo.erp.util.Tools;
import com.leo.erp.util.TreeNodeEx;

@Controller
@RequestMapping(value = "/user")
public class UserManagementController {
	@Autowired
	private UserService userService;
	@Autowired
	private TenantService tenantService;
	@Autowired
	private LogService logService;
	
	private boolean demonstrateOpen = false;
	
	@RequestMapping(value = "/getUserById")
	@ResponseBody
	public Map<String, Object> getUserById(HttpServletRequest request){
		Map<String, Object> modelMap = new HashMap<>();
		//获取前台传过来的值
		int userId = HttpServletRequestUtil.getInt(request, "userId");
		
		UserExecution ue = userService.getUserById(userId);
		if(ue.getState() == UserStateEnum.SUCCESS.getState()) {
			modelMap.put("success", true);
			modelMap.put("user", ue.getUser());
		}else {
			modelMap.put("success", false);
			modelMap.put("msg", "获取信息失败");
		}
		
		return modelMap;
	}
	
	@RequestMapping(value = "/getOrganizationUserTree")
	@ResponseBody
	public JSONArray getOrganizationUserTree() {
		JSONArray arr = new JSONArray();
		List<TreeNodeEx> organizationUserTree = userService.getOrganizationUserTree();
		if(organizationUserTree != null && organizationUserTree.size() > 0) {
			for(TreeNodeEx node : organizationUserTree) {
				String str = JSON.toJSONString(node);
                JSONObject obj = JSON.parseObject(str);
                arr.add(obj) ;
			}
		}
		return arr;
	}
	
	/**
     * 是否开启演示状态，默认关闭
     * @param request
     * @return
     */
	@RequestMapping(value = "/getDemonstrateOpen")
	@ResponseBody
	public Map<String, Object> getDemonstrateOpen(HttpServletRequest request){
		Map<String, Object> modelMap = new HashMap<>();
		try {
			modelMap.put("success", true);
			modelMap.put("demonstrateOpen", demonstrateOpen);
		} catch (GlobalRuntimeException e) {
			e.printStackTrace();
			modelMap.put("success", false);
			modelMap.put("msg", "获取失败");
		}
		
		return modelMap;
	}
	
	@RequestMapping(value = "/getUserNameById")
	@ResponseBody
	public Map<String, Object> getUserNameById(HttpServletRequest request){
		Map<String, Object> modelMap = new HashMap<>();
		//获取前台传过来的值
		int userId = HttpServletRequestUtil.getInt(request, "userId");
		
		UserExecution ue = userService.getUserNameById(userId);
		if(ue.getState() == UserStateEnum.SUCCESS.getState()) {
			modelMap.put("success", true);
			modelMap.put("userName", ue.getUser().getUserName());
		}else {
			modelMap.put("success", false);
		}
		
		return modelMap;
	}
	
	@RequestMapping(value = "/getAllList")
	@ResponseBody
	public Map<String, Object> getAllList(){
		Map<String, Object> modelMap = new HashMap<>();
		UserExecution ue = new UserExecution();
		
		ue = userService.getAllList();
		if(ue.getState() == UserStateEnum.SUCCESS.getState()) {
			modelMap.put("success", true);
			modelMap.put("userList", ue.getUserList());
		}else {
			modelMap.put("success", false);
			modelMap.put("msg", "查询数据失败");
		}
		return modelMap;
	}
	
	@RequestMapping(value = "/list")
	@ResponseBody
	public Map<String, Object> list(HttpServletRequest request){
		Map<String, Object> modelMap = new HashMap<>();
		//获取前台传过来的值
		int currentPage = HttpServletRequestUtil.getInt(request, "currentPage");
		int pageSize = HttpServletRequestUtil.getInt(request, "pageSize");
		String userName = HttpServletRequestUtil.getString(request, "userName");
		String loginName = HttpServletRequestUtil.getString(request, "loginName");
		
		UserExecution ue = new UserExecution();
		ue = userService.getList(userName, loginName, currentPage, pageSize);
		if(ue.getState() == UserStateEnum.SUCCESS.getState()) {
			modelMap.put("success", true);
			modelMap.put("pages",ue.getPages());//总页数
			modelMap.put("total", ue.getTotal());//总数
			
			Map<String, Object> map = new HashMap<>();
			map.put("rows", ue.getUserPageList());
			map.put("total", ue.getTotal());
			//modelMap.put("userList", ue.getUserPageList());
			modelMap.put("userList", map);
		}else {
			modelMap.put("success", false);
			modelMap.put("msg", "查询列表失败");
		}		
		return modelMap;
	}
	
	@RequestMapping(value = "/updateUser")
	@ResponseBody
	public Map<String, Object> updateUser(HttpServletRequest request){
		Map<String, Object> modelMap = new HashMap<>();
		//获取前台传过来的值
		String beanJson = HttpServletRequestUtil.getString(request, "info");
		int userId = HttpServletRequestUtil.getInt(request, "userId");
		User user = JSON.parseObject(beanJson, User.class);
		user.setUserId(userId);
		UserExecution ue = userService.updateUserAndOrgUserRel(user);
		if(ue.getState() == UserStateEnum.SUCCESS.getState()) {
			modelMap.put("success", true);
			modelMap.put("msg", "更改信息成功");
		}else {
			modelMap.put("success", false);
			modelMap.put("msg", "更改信息失败");
		}
		
		return modelMap;
	}
	
	@RequestMapping(value = "/resetPwd")
	@ResponseBody
	public Map<String, Object> resetPwd(HttpServletRequest request){
		Map<String, Object> modelMap = new HashMap<>();
		//获取前台传过来的值
		int userId = HttpServletRequestUtil.getInt(request, "id");
		
		String password = "123456";
		String md5Pwd;
		UserExecution ue = new UserExecution();
		try {
			md5Pwd = Tools.md5Encryp(password);
			ue = userService.resetPwd(md5Pwd, userId);
			if(ue.getState() == UserStateEnum.SUCCESS.getState()) {
				modelMap.put("success", true);
				modelMap.put("msg", "修改密码成功");
			}else {
				modelMap.put("success", false);
				modelMap.put("msg", "修改密码失败");
			}
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (GlobalRuntimeException e) {
			e.printStackTrace();
		}	
		return modelMap;
	}
	
	@RequestMapping(value = "/addUser")
	@ResponseBody
	public Map<String, Object> addUser(HttpServletRequest request){
		Map<String, Object> modelMap = new HashMap<>();
		String beanJson = HttpServletRequestUtil.getString(request, "info");
		int userNumLimit = Integer.parseInt(request.getSession().getAttribute("userNumLimit").toString());
		UserExecution userNum = userService.countUser(null, null);
		UserExecution ue = new UserExecution();
		int count = 0;
		if(userNum.getState() == UserStateEnum.SUCCESS.getState()) {
			count = userNum.getCount();
		}
		if(count >= userNumLimit) {
			modelMap.put("success", false);
			modelMap.put("msg", "用户录入数量超出限制，请联系管理员");
		}else {
			//插入数据
			User user = JSON.parseObject(beanJson, User.class);
			ue = userService.addUserAndOrgUserRel(user);
			if(ue.getState() == UserStateEnum.SUCCESS.getState()) {
				modelMap.put("success", true);
				modelMap.put("msg", "添加信息成功");
			}else {
				modelMap.put("success", false);
				modelMap.put("msg", ue.getStateInfo());
			}
		}		
		return modelMap;
	}
	
	@RequestMapping(value = "/deleteUser")
	@ResponseBody
	public Map<String, Object> deleteUser(HttpServletRequest request){
		Map<String, Object> modelMap = new HashMap<>();
		//获取前台传过来的值
		int userId = HttpServletRequestUtil.getInt(request, "ids");
		
		UserExecution ue = userService.deleteUser(userId);
		if(ue.getState() == UserStateEnum.SUCCESS.getState()) {
			modelMap.put("success", true);
			modelMap.put("msg", "用户信息删除成功");
		}else {
			modelMap.put("success", false);
			modelMap.put("msg", "删除失败");
		}	
		return modelMap;
	}
	
	@RequestMapping(value = "/registerUser")
	@ResponseBody
	public Map<String, Object> registerUser(HttpServletRequest request){
		Map<String, Object> modelMap = new HashMap<>();
		//获取前台传过来的值
		String loginName = HttpServletRequestUtil.getString(request, "loginName");
		String userName = HttpServletRequestUtil.getString(request, "userName");
		String password = HttpServletRequestUtil.getString(request, "password");
		
		User user = new User();
		if(loginName != null && loginName != "") {
			user.setLoginName(loginName);
		}
		if(userName != null && userName != "") {
			user.setUserName(userName);
		}
		if(password != null && password != "") {
			user.setPassword(password);
		}
		
		//检查用户名和登陆名是否可以使用
		UserExecution ue = userService.checkUserNameAndLoginName(userName, loginName, password);
		//判断返回的结果
		if(ue.getState() == UserStateEnum.USERNAME_EXIST.getState()) {
			modelMap.put("success", true);
			modelMap.put("state", 5);
			modelMap.put("msg", UserStateEnum.USERNAME_EXIST.getStateInfo());
		}else if(ue.getState() == UserStateEnum.USERNAME_LIMIT.getState()) {
			modelMap.put("success", true);
			modelMap.put("state", 7);
			modelMap.put("msg", UserStateEnum.USERNAME_LIMIT.getStateInfo());
		}else if(ue.getState() == UserStateEnum.LOGINNAME_EXIST.getState()) {
			modelMap.put("success", true);
			modelMap.put("state", 4);
			modelMap.put("msg", UserStateEnum.LOGINNAME_EXIST.getStateInfo());
		}else if(ue.getState() == UserStateEnum.LOGINNAME_LIMIT.getState()) {
			modelMap.put("success", true);
			modelMap.put("state", 6);
			modelMap.put("msg", UserStateEnum.LOGINNAME_LIMIT.getStateInfo());
		}else if(ue.getState() == UserStateEnum.SUCCESS.getState()) {	
			int manageRoleId = 10;
			userService.registerUser(user, manageRoleId, request);
			modelMap.put("success", true);
			modelMap.put("state", 1);
			modelMap.put("msg", "注册成功");
		}else {
			modelMap.put("success", false);
			modelMap.put("msg", "插入错误");
		}
		
		return modelMap;
	}
	
	@RequestMapping(value = "/login")
	@ResponseBody
	public Map<String, Object> login(HttpServletRequest request){
		Map<String, Object> modelMap = new HashMap<>();
		//获取前台传过来的值
		String loginName = HttpServletRequestUtil.getString(request, "loginName");
		String password = HttpServletRequestUtil.getString(request, "password");
		
		User user = null;
		loginName = loginName.trim();
		password = password.trim();
		
		//判断用户是否已经登录过,登录过不再处理
		Object userInfo = request.getSession().getAttribute("user");
		User sessionUser = new User();
		if(userInfo != null) {
			sessionUser = (User) userInfo;
		}
		
		if (sessionUser != null && loginName.equalsIgnoreCase(sessionUser.getLoginName())) {
            modelMap.put("success", true);
			modelMap.put("msg", "user already login");
        }else {
        	UserExecution ue = new UserExecution();
    		try {
    			request.getSession().removeAttribute("tenantId");
    			ue = userService.validateUser(loginName, password);
    			//查询返回的状态值
    			if(ue.getState() == UserStateEnum.SUCCESS.getState()) {
    				//验证通过,可以登陆,放入session,记录登陆日志
    				ue = userService.getUserByLoginName(loginName);
    				user = ue.getUser();
    				request.getSession().setAttribute("user", user);
    				
    				
    				if(user.getTenantId() > 0) {
    					TenantExecution te = tenantService.getTenantByTenantId(user.getTenantId());
    					if(te.getTenant() != null) {
    						int tenantId = te.getTenant().getTenantId();
    						int userNumLimit = te.getTenant().getUserNumLimit();
    						int billsNumLimit = te.getTenant().getBillsNumLimit();
    						if(tenantId > 0) {
    							request.getSession().setAttribute("tenantId",tenantId); //租户tenantId
                                request.getSession().setAttribute("userNumLimit",userNumLimit); //用户限制数
                                request.getSession().setAttribute("billsNumLimit",billsNumLimit); //单据限制数
    						}
    					}
    				}
    				//存储操作日志
    				logService.insertLog("用户", user.getLoginName() + "登陆了", ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest());
    				
    				modelMap.put("success", true);
    				modelMap.put("user", user);
    				modelMap.put("msg", "user can login");
    			}
    			if(ue.getState() == UserStateEnum.USER_NOT_EXIST.getState()) {
    				modelMap.put("success", false);
    				modelMap.put("msg", "user is not exist");
    			}
    			if(ue.getState() == UserStateEnum.USER_PASSWORD_ERROR.getState()) {
    				modelMap.put("success", false);
    				modelMap.put("msg", "user password error");
    			}
    		} catch (GlobalRuntimeException e) {
    			e.printStackTrace();
    		}
        }
	
		return modelMap;
	}
	
	@RequestMapping(value = "/logout")
	@ResponseBody
	public Map<String, Object> logout(HttpServletRequest request, HttpServletResponse response){
		Map<String, Object> modelMap = new HashMap<>();
		try {
            request.getSession().removeAttribute("user");
            request.getSession().removeAttribute("tenantId");
            request.getSession().removeAttribute("userNumLimit");
            request.getSession().removeAttribute("billsNumLimit");
            response.sendRedirect("../page/login");
        } catch(Exception e){
            e.printStackTrace();
            modelMap.put("success", false);
            modelMap.put("msg", "退出失败");
        }
		
		return modelMap;
	}
	
	@RequestMapping(value = "/getSessionUser")
	@ResponseBody
	public Map<String, Object> getSessionUser(HttpServletRequest request){
		Map<String, Object> modelMap = new HashMap<>();
		try {
			Object userInfo = request.getSession().getAttribute("user");
			if(userInfo != null) {
				User user = (User) userInfo;
				user.setPassword(null);
				modelMap.put("success", true);
				modelMap.put("user", user);
			}else {
				modelMap.put("success", false);
				modelMap.put("msg", "获取session失败");
			}
		} catch (GlobalRuntimeException e) {
			e.printStackTrace();
		}
		
		return modelMap;
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
}
